package com.ken.mqbase.direct;

import com.ken.constant.RabbitConstant;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;

/**
 * direct直连的方式（消费者）
 * Created by renchongyu on 2018/11/12.
 */
public class ConsumerDirect {

    public static void main(String[] args) throws Exception{
        //1.创建一个ConnectionFactory
        ConnectionFactory conn = new ConnectionFactory();
        conn.setHost(RabbitConstant.RABBITMQ_IP);
        conn.setPort(RabbitConstant.RABBITMQ_PORT);
        conn.setUsername(RabbitConstant.RABBITMQ_USER_NAME);
        conn.setPassword(RabbitConstant.RABBITMQ_USER_PASSWORD);
        conn.setVirtualHost(RabbitConstant.RABBITMQ_VIRTUAL_HOST);

        conn.setAutomaticRecoveryEnabled(true);//是否断开重连
        conn.setNetworkRecoveryInterval(3000);//重连时间3秒（3000毫秒）
        //2.通过连接工厂连接
        Connection connection = conn.newConnection();

        //3.通过连接创建一个channel
        Channel channel = connection.createChannel();
        //4.声明
        String exchangeName = "test_direct_exchange";//路由
        String exchangeType = "direct";//类型为直连
        String queueName = "test_direct_queue";//队列名称
        String routingKey = "test.direct";//路由键

        //表示声明了一个交换机
        channel.exchangeDeclare(exchangeName,exchangeType,true,false,false,null);

        //表示声明一个队列
        channel.queueDeclare(queueName,false,false,false,null);

        //建立一个绑定关系
        channel.queueBind(queueName,exchangeName,routingKey);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName,true,consumer);

        //获取消息
        while(true){
            Delivery delivery =consumer.nextDelivery();//阻塞制获取消息
            String msg = new String(delivery.getBody());
            System.out.println(msg);
        }
    }
}
